import fetch from '@system.fetch';
const SECRET_KEY = __APP_SECRETE_KEY__;
const BASE_URL = `${__TAC_BASE_URL__}`;

class AdManager {
  constructor() {
    this.adCycleState = 0; // 广告循环状态 0: 无广告 1: 有广告
    this.adData = null; // 广告数据
    this.adIdList = null; // 广告位列表
    this.videoAd = null; // 视频广告数据
    this.videoClose = true; // 视频广告是否自动关闭
  }

  /**
   * 展示二级页广告
   * @param {*} adRequest 广告请求对象, 包含获取自定义广告和插屏广告的方法,封装了优量汇等第三方广告SDK实现平台隔离
   */
  async showSubAd(adRequest) {
    this.adData = null;
    try {
      if (this.adCycleState === 0) {
        const ad = await adRequest.getCustomAd(); // 获取自定义广告
        if (ad) {
          this.adCycleState = 1;
          this.adData = ad;
        }
      } else {
        // 有广告循环状态时，展示插屏广告
        const ad = await adRequest.getInterstitial(); // 获取插屏广告
        if (ad) {
          this.adData = ad;
          this.adCycleState = 0;
        }
      }
    } catch (error) {
      console.error('业务广告 == 二级页广告error', error);
    }
  }

  getAdData() {
    return this.adData;
  }
  getVideoAdData() {
    return this.videoAd;
  }
  setVideoClose(status) {
    this.videoClose = status;
  }
  setVideoAdData(data) {
    this.videoAd = data;
  }

  clearAdData() {
    this.adData = null;
  }
  //广告位获取
  getAdId(ads) {
    return this.adIdList ? this.adIdList[ads] || '' : '';
  }
  getList() {
    return this.adIdList;
  }
  async getAdIdList() {
    try {
      if (!this.adIdList) {
        const response = await this.fetchApi(__TAC_PAGE_AD_CONFIG_URL__);

        if (response && response.code === 200) {
          try {
            const decodeTextConfig = SDK_TACTICS.getDecodeTextConfig(response.data.data);
            this.adIdList = decodeTextConfig || {};
          } catch (error) {
            this.adIdList = response.data.data || {};
          }
          console.log('业务广告 == 广告位获取', this.adIdList);
        }
      }
    } catch (error) {
      console.error('业务广告 == 广告位获取失败', error);
      return '';
    }
  }
  async fetchApi(url, method = 'post', data = {}) {
    const param = {
      secretKey: SECRET_KEY,
      mobilFactory: __CURRENT_BRAND__,
      ...data,
    };
    try {
      const encodeParams = SDK_TACTICS.getEncodeParam(param);
      for (const key in param) {
        delete param[key];
      }
      param.encode = encodeParams;
    } catch (error) {
      console.error('业务广告 == API == ERROR', error);
      throw new Error('业务广告 == API request failed');
    }
    try {
      let response = await fetch.fetch({
        url: BASE_URL + url,
        responseType: 'json',
        data: param,
        method: method,
        header: {
          'Content-Type': 'application/json',
        },
      });
      return response.data;
    } catch (error) {
      console.error('业务广告 == API == ERROR', error);
      throw new Error('业务广告 == API request failed');
    }
  }
}

// 广告管理实例
const adManagerInstance = new AdManager();

const UTILS_global = global.__proto__ || global; // 全局对象
UTILS_global.ADMANAGER = adManagerInstance; // 挂载广告管理实例到全局对象
export default adManagerInstance; // 导出广告管理实例
